package com.gdcp.controller.portal;

import com.gdcp.beans.*;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.service.*;
import com.gdcp.util.RandomNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Controller
@RequestMapping("/render/cart/")
public class CartController {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    ProductService productService;
    @Autowired
    CartService cartService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    ShippingService shippingService;
    @Autowired
    OrderService orderService;

    //购物车相关
    @RequestMapping(value = "/addCart",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> addCart(Integer pid, Integer num) {
        Product product = productService.productInfoById(pid);
        User user = (User) RequestHolder.getSession("user");
        //获取原来就在购物车的数据
        Cart cartItem = cartService.getOne(user.getId(), product.getId());
        Boolean isInDB = cartItem != null;

        //判断是否超出库存
        if (isInDB) {
            //现在+以前
            num += cartItem.getQuantity();
        } else {
            cartItem = new Cart();
            cartItem.setProduct_id(product.getId());
            cartItem.setUser_id(user.getId());
            cartItem.setChecked(1);
            cartItem.setProduct(product);
            cartItem.setUser(user);
        }

        //是否大于库存
        if (num > product.getStock()) {
            return responseModel.setModel(false,"超出库存范围");
        }

        cartItem.setQuantity(num);

        if (isInDB) {
            return cartService.update(cartItem);
        }

        return cartService.add(cartItem);
    }

    @RequestMapping(value = "/deleteCart",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> deleteCart(Integer id){
        try {
            return cartService.deleteCartById(id);
        }catch (Exception e){
            return responseModel.setModel(false,"删除失败");
        }
    }

    @RequestMapping(value = "/changeCartNum",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> changeCartNum(String ciid, String num){

        if (ciid==null||ciid.equals("")){
            return responseModel.setModel(false,"ciid不能为空");
        }

        if (num==null||num.equals("")){
            return responseModel.setModel(false,"num不能为空");
        }

        //HttpServletRequest request=RequestHolder.getRequest();
        Integer ciidCart= Integer.valueOf(ciid);
        Integer numCart= Integer.valueOf(num);
        Cart cartItemFromDB = cartService.queryByid(ciidCart);

        Product product = productService.productInfoById(cartItemFromDB.getProduct_id());
        cartItemFromDB.setProduct(product);
        if (cartItemFromDB.getProduct()!=null&&cartItemFromDB.getProduct().getStock()!=null&&cartItemFromDB.getProduct().getStock() >= numCart) {
            cartItemFromDB.setQuantity(numCart);
            try {
                cartService.update(cartItemFromDB);
            }catch (Exception e){
                e.printStackTrace();
                return responseModel.setModel(true,"库存不足");
            }
            return responseModel.setModel(false,"增加成功");
        }

        return responseModel.setModel(true,"库存不足");
    }

    @RequestMapping(value = "/buyOne",method = RequestMethod.GET)
    public String buyOne(Integer pid, Integer num) {
        Product product = productService.getInformation(pid);
        //System.out.println("product="+product);
        User user = (User) RequestHolder.getSession("user");

        /*cart----order----orderItem*/
        /*if(num<product.getStock()){
            return responseModel.setModel(false,"库存超出");
        }*/
        Cart cart = new Cart();
        cart.setUser_id(user.getId());
        cart.setProduct(product);
        cart.setQuantity(num);
        cart.setId(-1);
        RequestHolder.setSession("tempCartItem", cart);
        return "redirect:buy?ciid=-1";
    }

    @RequestMapping(value = "/buy",method = RequestMethod.GET)
    public String buy(Integer[] ciid, HttpServletRequest request) {
        List<Cart> carts = new ArrayList<>();
        int totalNum = 0;
        BigDecimal sumTotal= BigDecimal.valueOf(0);
        request.setAttribute("ciid",2);

        for (Integer id : ciid) {
            Cart cart;
            if (id == -1) {
                request.setAttribute("ciid",id);
                //由buyOne跳转而来---直接购买
                cart = (Cart) RequestHolder.getSession("tempCartItem");

            } else {
                //由购物车跳转而来
                cart = cartService.queryByid(id);
                Product product = productService.productInfoById(cart.getProduct_id());
                cart.setProduct(product);
            }

            totalNum += cart.getQuantity();
            String quantity= String.valueOf(cart.getQuantity());
            String price= cart.getProduct().getPrice();
            BigDecimal quantity_big=new BigDecimal(quantity);
            BigDecimal price_big=new BigDecimal(price);
            BigDecimal sum = quantity_big.multiply(price_big);
            sumTotal = sumTotal.add(sum);

            //System.out.println("cart="+cart.getProduct().getId());
            cart.setProduct_id(cart.getProduct().getId());
            carts.add(cart);
        }
        RequestHolder.setSession("cartItems", carts);
        request.setAttribute("totalNum", totalNum);
        request.setAttribute("sum", sumTotal);

        return "frontend/flow_centre";
    }

    @RequestMapping(value = "/flow",method = RequestMethod.GET)
    public String flow(){
        HttpServletRequest request=RequestHolder.getRequest();
        User user = (User) RequestHolder.getSession("user");
        Integer uid=user.getId();
        List<Cart> cart=cartService.queryByUid(uid);
        request.setAttribute("cart",cart);
        return "frontend/flow";
    }
}